package mini.expr.math;

import mini.Program;
import mini.compiler.CodeGenerator;
import mini.expr.Expr;

import java.util.HashMap;

public class Minus extends Expr {

    private Expr e1, e2;

    public Minus (Expr op1, Expr op2){
    	super();
    	e1 = op1;
    	e2 = op2;
    }
    
    public Integer eval(HashMap hm){
    	return new Integer(e1.eval(hm)-e2.eval(hm));
    }
    
    /**
     * Parse routine from slide 8 is:
     * <ol>
     * <li>Store result of op1 in t1
     * <li>Store result of op2 in t2
     * <li>Load result of op1 (stored in t1) to accumulator
     * <li>Subtract from it result of op2 (stored in t2)
     * <li>Store accumulator to t3
     * </ol>
     */
    public String parse(HashMap hm) {
    	
    	CodeGenerator cg = new CodeGenerator();
    	
    	// Keep track of the temp variable
    	hm.put(getTempVariable(), null);

    	// Load operands 1 and 2 to memory
    	cg.appendCode( e1.parse(hm) );
    	cg.appendCode( e2.parse(hm) );
    	
    	// Load operand 1 to the accumulator
    	cg.addLoadAccumulator( e1.getTempVariable() );
    	
    	// Subtract operand 2 from the accumulator
    	cg.addSubtract( e2.getTempVariable() );
    	
    	// Store the result
    	cg.addStoreAccumulator( getTempVariable() );
    	
    	// Return the result
    	return cg.getCode();
    }
}
